#Copyright 2012 Elias Farhan
#
#This file is part of Squirrel.
#
#Squirrel is free software: you can redistribute it and/or modify it under the terms of the GNU General 
#Public License as published by the Free Software Foundation, either version 3 of the License, or (at your 
#option) any later version.
#
#Squirrel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
#without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
#See the GNU General Public License for more details.
import pygame
import Tkinter
import lxml.etree as ET
import threading
import sys
sys.path.insert(0, '..')
from client.game.gameobject import Character, GameObject
from client.game.box import Box
from client.game.xmlreader import XML2level, XML2char
from toXML import level2XML, char2XML
from client.game.level import Level

lock = threading.Lock()
level = None
currentGameObject = -1
currentBox = -1

class SpriteBox(pygame.sprite.Sprite):
	#blue box for hitbox
	#red box for damagebox
	#grey box for collisionbox
	def __init__(self, initial_pos):
		self.pos = initial_pos
		self.origin = self.pos
		self.end = (self.pos[0]+2, self.pos[1]+2)
		self.image = pygame.Surface((2, 2))
	def setpos(self, pos):
		if((pos[0]<self.pos[0]) and (pos[1]<self.pos[1])):
			self.origin = pos
			self.end = self.pos
		elif((pos[0]>self.pos[0]) and (pos[1]>self.pos[1])):
			self.origin = self.pos
			self.end = pos
		elif((pos[0]>self.pos[0]) and (pos[1]<self.pos[1])):
			self.origin = (self.pos[0], pos[1])
			self.end = (pos[0], self.pos[1])
		else:
			self.end = (self.pos[0], pos[1])
			self.origin = (pos[0], self.pos[1])
		if(self.end[0] == self.origin[0]):
			self.end= (self.end[0]+2, self.end[1])
		if(self.end[1] == self.origin[1]):
			self.end= (self.end[0], self.end[1]+2)
		self.image = pygame.Surface((self.end[0]-self.origin[0], self.end[1]-self.origin[1]))
		self.image.fill((0, 0, 255))
		self.image.set_alpha(100)
		self.rect = self.image.get_rect()
		
class TkinterWindow(threading.Thread):
	def __init__(self):
		threading.Thread.__init__(self)
	def getcurrent(self):
		global level, lock
		lock.acquire()
		if (level != None):
			i, select = 0, 0
			while (i<self.gameobjectlistbox.size()):
				if(self.gameobjectlistbox.selection_includes(i)):
					select = True
					break
				i+=1

			if(select):
				currentGameObject = i
			else:
				currentGameObject = -1
			i, select = 0, 0
			while (i<self.currentboxlistbox.size()):
				if(self.currentboxlistbox.selection_includes(i)):
					select = True
					break
				i+=1

			if(select):
				currentBox = i
			else:
				currentBox = -1
		lock.release()
	def importGameObject(self):
		global level, lock
		#First we search if the gameobject is a character
		filename = self.currentloadentry.get()
		try:
			c = XML2char("../data/xml/character/"+filename+".xml")
			c.setImage("../data/sprites/"+filename+"111.png")
			#TODO if it is the player
		except IOError:
			#if it is not a saved character, then it is a game object, so:
			image = pygame.image.load("../data/sprites/"+filename+".png")
			size = image.get_size()
			pos = (0,0)
			gameobject = GameObject(pos, size, filename)
			gameobject.setImage(image)
			lock.acquire()
			level.gameobjects.append(gameobject)
			lock.release()
			self.gameobjectlistbox.insert(Tkinter.END, gameobject.filename)			
	def importLevel(self):
		global lock, level, currentBox, currentGameObject
		self.currentboxlistbox.delete(0, self.currentboxlistbox.size())
		self.gameobjectlistbox.delete(0, self.gameobjectlistbox.size())
		filename = self.label.get()
		try:
			l = XML2level("../data/xml/level/"+filename+".xml")
			for gameobject in l.gameobjects:
				image = pygame.image.load("../data/sprites/"+gameobject.filename+".png")
				gameobject.setImage(image)
				self.gameobjectlistbox.insert(Tkinter.END, gameobject.filename)
			for character in l.characters:
				image = pygame.image.load("../data/sprites/"+gameobject.filename+"111.png")
				character.setImage(image)
		except IOError:
			l = Level(filename)
		lock.acquire()
		level = l
		currentBox = -1
		currentGameObject = -1
		lock.release()
	def save(self):
		global level, lock
		filename = "../data/xml/level/"+self.label.get()+".xml"
		lock.acquire()
		#save level
		(level2XML(level)).write(filename)
		lock.release()
	def run(self):
		global currentState
		self.tk = Tkinter.Tk()
		self.load = Tkinter.Toplevel()
		#self.load.pack()
		
		self.label = Tkinter.Entry(self.load)
		self.label.pack()
		self.button = Tkinter.Button(self.load, text="Load", command=self.importLevel)#, command=self.loadprocess)

		self.button.pack()
		
		self.stat = Tkinter.Frame(self.tk)
		self.stat.pack()
		
		self.state = Tkinter.Frame(self.stat)
		self.statelabel = Tkinter.Label(self.state, text="GameObject")
		self.stentry = Tkinter.StringVar()
		self.stateentry = Tkinter.Label(self.state, text="NULL", textvariable =self.stentry)
		self.statelabel.pack(side="left")
		self.stateentry.pack(side="right")
		self.state.pack()
		
		self.pos = Tkinter.Frame(self.stat)
		self.poslabel = Tkinter.Label(self.pos, text="Pos")
		self.posentry = Tkinter.Entry(self.pos)
		self.poslabel.pack(side="left")
		self.posentry.pack(side="right")
		self.pos.pack()
		
		self.size = Tkinter.Frame(self.stat)
		self.sizelabel = Tkinter.Label(self.size, text="Size")
		self.sizeentry = Tkinter.Entry(self.size)
		self.sizelabel.pack(side="left")
		self.sizeentry.pack(side="right")
		self.size.pack()
		
		self.gameobject = Tkinter.Frame(self.stat)
		self.gameobjectlistbox = Tkinter.Listbox(self.gameobject)
		self.gameobjectlistbox.pack()
		self.gameobject.pack()
		
		self.mousepos = Tkinter.Frame(self.stat)
		self.mptext = Tkinter.StringVar()
		self.mousepostext = Tkinter.Label(self.mousepos, textvariable=self.mptext)
		self.mousepostext.pack()
		self.mousepos.pack()
		
		self.savebutton = Tkinter.Button(self.stat, text="Save", command=self.save)
		self.savebutton.pack()
		
		self.boxwindow = Tkinter.Toplevel()
		self.currentboxlabel = Tkinter.Label(self.boxwindow, text="Box")
		self.currentboxentry = Tkinter.Entry(self.boxwindow)
		self.currentboxlistbox = Tkinter.Listbox(self.boxwindow, selectmode=Tkinter.SINGLE)
		self.currentboxlabel.pack()
		self.currentboxentry.pack()
		self.currentboxlistbox.pack()

		self.loadwindow = Tkinter.Toplevel()
		self.currentloadlabel = Tkinter.Label(self.loadwindow, text="Load GameObject")
		self.currentloadentry = Tkinter.Entry(self.loadwindow) 
		self.loadbutton = Tkinter.Button(self.loadwindow, text="Load", command=self.importGameObject)

		self.currentloadlabel.pack()
		self.currentloadentry.pack()
		self.loadbutton.pack()
		self.tk.mainloop()
	def getSelectedGameObject(self):
		return self.gameobjectlistbox.curselection()
def main():
	tkinter = TkinterWindow()
	tkinter.start()
	pygame.init()
	fpsClock = pygame.time.Clock()
	screen = pygame.display.set_mode((1000, 700))
	screen_speed = 10
	background = pygame.Surface(screen.get_size())
	background = background.convert()
	background.fill((250, 250, 250))
	pygame.display.set_caption('Level Editor v0.2')
	screen.blit(background, (0, 0))
	pygame.display.flip()
	over = False
	screen_pos = (0, 0)
	direction = [0, 0, 0, 0]#UP, DOWN, RIGHT, LEFT
	while not over :
		fpsClock.tick(60)
		screen.blit(background, (0, 0))
		for event in pygame.event.get():
			if (event.type == pygame.KEYDOWN):
				if(event.key == pygame.K_UP):
					direction[0] = True
				elif (event.key == pygame.K_DOWN):
					direction[1] = True
				elif (event.key == pygame.K_RIGHT):
					direction[2] = True
				elif (event.key == pygame.K_LEFT):
					direction[3] = True
			elif (event.type == pygame.KEYUP):
				if(event.key == pygame.K_UP):
					direction[0] = False
				elif (event.key == pygame.K_DOWN):
					direction[1] = False
				elif (event.key == pygame.K_RIGHT):
					direction[2] = False
				elif (event.key == pygame.K_LEFT):
					direction[3] = False
			elif (event.type == pygame.MOUSEBUTTONDOWN):
				print pygame.mouse.get_pos(), pygame.mouse.get_pressed(), pygame.mouse.get_rel()
			elif (event.type == pygame.MOUSEBUTTONUP):
				pass
		screen_pos = (screen_pos[0] + screen_speed * (direction[2]-direction[3]), \
					  screen_pos[1] + screen_speed * (direction[1]-direction[0]))
					  
		tkinter.getcurrent()
		#draw the rest
		lock.acquire()
		print currentGameObject
		if (level != None):
			for gameobject in level.gameobjects:
				if(gameobject.image != None):
					screen.blit(gameobject.image, (gameobject.pos[0]-screen_pos[0], gameobject.pos[1]-screen_pos[1]))
			for character in level.characters:
				if(character.image != None):
					screen.blit(character.image, (character.pos[0]-screen_pos[0], character.pos[1]-screen_pos[1]))
			if(level.player != None):
				screen.blit(level.player.image, (level.player.pos[0]-screen_pos[0], level.player.pos[1]-screen_pos[1]))
		lock.release()
		pygame.display.flip()
if __name__ == "__main__":
	main()
